package cn.tedu.d21_socket.demo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/*
 服务器端
 */
public class Server {

    ServerSocket server;/*服务器套接字*/
    //第6需求添加属性
    List<PrintWriter> list;


    public Server(){

        try {
            System.out.println("监听8080端口中...");
            server=new ServerSocket(8080);

            list=new ArrayList<>();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start(){

        try {
            while (true) {
                System.out.println("等待客户端连接...");
                /*返回一个和客户端交互的Socket*/
                Socket socket = server.accept();//阻塞方法
                System.out.println("客户端已连接");

                ClientHandler ch = new ClientHandler(socket);
                Thread t = new Thread(ch);
                t.start();
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }




    class ClientHandler implements Runnable{
        Socket socket;
        public ClientHandler(Socket s){
            this.socket=s;//初始化Socket
        }
        public void run(){
            //获取字节输入流
            PrintWriter pw=null;
            try {
                InputStream is = socket.getInputStream();
                BufferedInputStream bis=new BufferedInputStream(is);
                InputStreamReader isr=new InputStreamReader(bis,"utf-8");
                BufferedReader br=new BufferedReader(isr);
                //服务器端先读再写
                OutputStream os= socket.getOutputStream();
                BufferedOutputStream bos=new BufferedOutputStream(os);
                OutputStreamWriter osw=new OutputStreamWriter(bos,"utf-8");
                pw=new PrintWriter(osw,true);

                list.add(pw);
                String line=null;
                while (true){
                    line=br.readLine();
//                    System.out.println("服务器说："+line);
                    //pw.println(line);
                    //遍历集合中的输出流，将内容以广播形式写给客户端
                    System.out.println(socket.getInetAddress().getHostAddress()+":"+line);
                    for (PrintWriter p:list) {
                        p.println(line);
                    }
                }

            } catch (IOException e) {
                //e.printStackTrace();
                System.out.println("下线了");
                list.remove(pw);
                pw.close();
            }
        }
    }

    public static void main(String[] args) {
        Server s=new Server();
        s.start();
    }
}
